import { useState } from 'react'

/**
 * 使用本地存储,并设置过期时间
 *
 * @param {string} key - 本地存储的键名
 * @param {any} initialValue - 默认值
 * @param {number} ms - 以毫秒为单位的时间将值保留在本地存储中
 * @returns {[any, (value: any) => void]}
 */
export const useLocalStorage = (key, initialValue, ms = 5000) => {
  const expiredAt = new Date().getTime() + (ms === -1 ? 86400 * 365 * 1000 : ms)

  const [storedValue, setStoredValue] = useState(() => {
    try {
      const val = window.localStorage.getItem(key)
      const { expired_at, value } = JSON.parse(val)

      if (expired_at && new Date().getTime() > expired_at) {
        window.localStorage.removeItem(key)
        return initialValue
      }

      return value
    } catch (error) {
      return initialValue
    }
  })

  const setValue = (value) => {
    const valueToStore = value instanceof Function ? value(storedValue) : value

    if (valueToStore === undefined) {
      window.localStorage.removeItem(key)
      setStoredValue(initialValue)
      return
    }

    try {
      setStoredValue(valueToStore)
      const newValue = { expired_at: expiredAt, value: valueToStore }
      window.localStorage.setItem(key, JSON.stringify(newValue))
    } catch (error) {
      console.error(error)
    }
  }

  return [storedValue, setValue]
}
